package manager


import android.app.ActivityManager
import android.content.Context
import app.AppContext
import mvc.model.CpuInfo
import java.io.BufferedReader
import java.io.FileReader

object CpuManager : Runnable {
    val Pid = android.os.Process.myPid()

    val USER_CPU_PATH = "/proc/$Pid/stat"
    const val CPU_PATH = "/proc/stat"
    const val TEMP_PATH = "/sys/class/thermal/thermal_zone0/temp"

    var cpuInfo: String = "0/0"
        get() {
            return "$rate%/$appRate%/$tempValue℃"
        }

    var memoryInfo: String = "0/0/0"
        get() {
            return "${totalMemory / 1024 / 1024}MB/${avaliMemory / 1024 / 1024}MB/$memoryRate%"
        }

    var rate = "0.0"
        get() {
            val s =
                100.0f * (info.takeTime - lastInfo.takeTime).toFloat() / (info.totalTime - lastInfo.totalTime).toFloat()
            return String.format("%.2f", s)
        }

    var appRate = "0.0"
        get() {
            val s =
                100.0f * (appTime - lastAppTime).toFloat() / (info.totalTime - lastInfo.totalTime).toFloat()
            return String.format("%.2f", s)
        }

    var tempValue: String = ""

    var totalMemory: Long = 1

    var avaliMemory: Long = 1

    var memoryRate = "0.0"
        get() {
            return String.format("%.2f", (1 - avaliMemory.toFloat() / totalMemory.toFloat()) * 100f)
        }

    var lastInfo = cpuInfo()
    var lastAppTime: Long = 0

    var appTime: Long = 0
    var info = lastInfo

    private fun cpuInfo(): CpuInfo {
        val reader = BufferedReader(FileReader(CPU_PATH))
        val cpu = reader.readLine()
        reader.close()
        return CpuInfo(cpu)
    }

    private fun appCpuTime(): Long {
        val reader = BufferedReader(FileReader(USER_CPU_PATH))
        val cpu = reader.readLine()
        reader.close()
        val lists = cpu.split(" ")
        return lists[13].toLong() + lists[14].toLong() + lists[15].toLong() + lists[16].toLong()
    }

    private fun cpuTempValue() {
        val reader = BufferedReader(FileReader(TEMP_PATH))
        val s = reader.readLine()
        reader.close()
        tempValue = s
    }

    private fun memoryInfo() {
        val am = AppContext.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val mi = ActivityManager.MemoryInfo()
        am.getMemoryInfo(mi)
        totalMemory = mi.totalMem
        avaliMemory = mi.availMem
    }

    override fun run() {
        try {
            lastInfo = info
            info = cpuInfo()

            lastAppTime = appTime
            appTime = appCpuTime()

            if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.LOLLIPOP) {
                cpuTempValue()
            }

            memoryInfo()

            AsyncTask.postDelayed(this, 1000)
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }
}